package com.example.medicalzb.controller;

import com.example.medicalzb.domain.DrugCompany;
import com.example.medicalzb.service.CompanyService;
import com.example.medicalzb.util.Msg;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;

@RestController
@RequestMapping("/api/companys")
@Api(tags = "医药公司信息控制器")
@CrossOrigin
public class CompanyController {
    @Autowired
    private CompanyService companyService;

    //医药公司信息分页查询
    @GetMapping(value = {"/{pn}/{size}",""})
    public Msg getCompanyWithPage(@PathVariable(value = "pn",required = false) Integer pn,
                                  @PathVariable(value = "size",required = false) Integer size,
                                  @RequestParam(required = false) String name){
        PageInfo<DrugCompany> pageInfo = companyService.getCompanyWithPage(pn,size,name);
        if (pageInfo != null){
            return Msg.success().data("pageInfo",pageInfo);
        }
        return Msg.fail();
    }

    //根据id查询公司
    @GetMapping("{id}")
    public Msg getCompanyById(@PathVariable("id") Integer id){
        return companyService.getCompanyById(id);
    }

    //添加公司
    @RolesAllowed({"1"})
    @PostMapping(value = "")
    public Msg saveCompany(@RequestBody DrugCompany drugCompany){
        String name = drugCompany.getCompanyName();
        String phone = drugCompany.getCompanyPhone();
        if (name == null || phone == null || name.equals("") || phone.equals("")){
            return Msg.fail().mess("请确保填入的信息完整");
        }
        return companyService.saveCompany(drugCompany);
    }

    //修改公司信息
    @RolesAllowed({"1"})
    @PutMapping(value = "{id}")
    public Msg updateCompany(@PathVariable("id") Long id, @RequestBody DrugCompany drugCompany){
        if (drugCompany.getCompanyName() == null || drugCompany.getCompanyName().equals("")){
            return Msg.fail().mess("公司名称不能为空");
        }
        if (drugCompany.getCompanyPhone() == null || drugCompany.getCompanyPhone().equals("")){
            return Msg.fail().mess("公司电话号不能为空");
        }
        return companyService.updateCompany(id,drugCompany);
    }

    //删除公司
    @RolesAllowed({"1"})
    @DeleteMapping("{id}")
    public Msg deleteCompanyById(@PathVariable("id") Integer id){
        return companyService.deleteCompanyById(id);
    }
}
